package com.shareppy.normanhttp.tasks;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.shareppy.normanhttp.R;
import com.shareppy.utils.StringUtils;

public abstract class SppyBgTask<PARAMS extends BgTaskParams, RESULT> extends AsyncTask<PARAMS, Void, RESULT> {

	public static final int DEFAULT_TASK = 0;
	private ProgressDialog loading;
	private Context context;
	private int activityId;
	private String dialogTitle;
	private String dialogText;
	private String workingMessage;
	private boolean hasContext;

	public SppyBgTask(Context context) {
		this.context = context;
		this.hasContext = this.context != null;
		if (this.hasContext) {
			setDialogText(context.getString(R.string.loading));
		}
	}

	@Override
	protected void onPreExecute() {
		if (this.hasContext) {
			super.onPreExecute();
			loading = ProgressDialog.show(
					this.context,
					context.getString(R.string.please_wait),
					StringUtils.isEmpty(workingMessage) ? context
							.getString(R.string.loading) : workingMessage);
			loading.setIndeterminate(true);
		}
	}

	@Override
	protected void onPostExecute(RESULT result) {
		if (this.hasContext) {
			super.onPostExecute(result);
			try {
				loading.dismiss();
			} catch (Exception e) {
				//
			}
		}
	}

	@Override
	protected RESULT doInBackground(PARAMS... params) {
		publishProgress();
		if (params == null) {
			return run(null);
		}
		return run(params[0]);
	}

	protected abstract RESULT run(PARAMS params);

	// ///////////////////////////////////////////////////////////
	public <T extends SppyBgTask<PARAMS, RESULT>> T cloneTask() {
		return null;
	}

	public void setActivityId(int activityId) {
		this.activityId = activityId;
	}

	public int getActivityId() {
		return activityId;
	}

	public String getDialogTitle() {
		return dialogTitle;
	}

	public void setDialogTitle(String dialogTitle) {
		this.dialogTitle = dialogTitle;
	}

	public String getDialogText() {
		return dialogText;
	}

	public void setDialogText(String dialogText) {
		this.dialogText = dialogText;
	}

	public Context getContext() {
		return context;
	}

	public void setWorkingMessage(String workingMessage) {
		this.workingMessage = workingMessage;
	}
}